﻿$(function () {
//When DOM has loaded, javascript checks if there is any new notifications every 6th second
    window.setInterval(function () {
        getNotifications();
        getNewFriends();
    }, 6000);

    var cache = {};
    //Calls for validation when something changes in the message text recipient dialog.
    $('#MainContent_messagestxtRecipient').blur(function () { validateMessageRecipient() });
    $('#MainContent_messagestxtRecipient').keyup(function () { validateMessageRecipient() });

});         // end startup

function showPremiumHistory() {
    $('#settingsPremiumHistory').slideToggle();
}

// Fires when text is entered in recipient field
function validateMessageRecipient() {

    
    var input = $('#MainContent_messagestxtRecipient');

    //If text has been entered
    if ($('#MainContent_messagestxtRecipient').val().length > 0) {
        //Make a call to ajax.aspx with getJSON-method
        $.getJSON(
                    'ajax.aspx',
                    //Call finduser-method in ajax.aspx, with inputvalue as param
                    { call: "FindUser", query: $('#MainContent_messagestxtRecipient').val() },
                    function (data) {

                        //If user is found, show ok-icon
                        if (data.Username != null) {
                            $('#messages-foundUserStatus').attr({
                                src: '/images/icons/Accept-big.png',
                                class: 'foundUserStatusVisible',
                                title: 'Användaren hittades'
                            });
                            //Let user send message
                            $('#MainContent_hiddenUserID').val(data.UserID);
                            $('#MainContent_btnSendMessage').removeAttr('disabled');
                        }
                        else {
                            $('#messages-foundUserStatus').attr({
                                src: '/images/icons/Cancel-icon.png',
                                class: 'foundUserStatusVisible',
                                title: 'Användaren hittades inte'
                            });
                            $('#MainContent_btnSendMessage').attr('disabled', 'disabled');
                        }
                    }
                )
    }
}

//Gets new friendrequests using JSON-call to ajax.aspx
function getNewFriends() {
    var queryString = 'ajax.aspx';

    $.getJSON(
        queryString,
        { call: "newFriends" },
        function (data) {

            $('#friendRequestDiv').html(data.Username);

        });
}

//Checks if there is any new notifications and displays that. 
function getNotifications(user) {

    var queryString = 'ajax.aspx';

    $.getJSON(
queryString,
{ call: "notifications", id: user },
function (data) {

    if (data.Messages == true) {
        $('#notificationMessage').attr({
            src: '/images/icons/newmessage.png',
            alt: 'Du har nya meddelanden',
            title: 'Du har nya meddelanden'
        });

    }
    else {
        $('#notificationMessage').attr({
            src: '/images/icons/newmessage_inactive.png',
            alt: 'Det finns inga nya meddelanden',
            title: 'Det finns inga nya meddelanden'
        });

    }

    if (data.Friends == true) {
        $('#notificationFriend').attr({
            src: '/images/icons/newfriend.png',
            alt: 'Det finns en eller flera vänförfrågningar',
            title: 'Det finns en eller flera vänförfrågningar'
        });
    }
    else {
        $('#notificationFriend').attr({
            src: '/images/icons/newfriend_inactive.png',
            alt: 'Du har inga nya vänförfrågningar :(',
            title: 'Du har inga nya vänförfrågningar :('
        });
    }
    if (data.WallMessage == true) {
        $('#notificationWallMessage').attr({
            src: '/images/icons/newwallmessage.png',
            alt: 'Du har ett eller flera olästa gästbokinlägg',
            title: 'Du har ett eller flera olästa gästbokinlägg'
        });

    }
    else {
        $('#notificationWallMessage').attr({
            src: '/images/icons/newwallmessage_inactive.png',
            alt: 'Du har inga nya gästbokinlägg',
            title: 'Du har inga nya gästbokinlägg'
        });

    }
});
};

//Tells the user that a message has been sent.
function showNotificationMessage(message) {
    $('#pageNotificationMessage').html('<img src="/images/icons/Accept.png" />&nbsp;' + message);
    $('#pageNotificationMessage').slideDown("fast");
    $('#pageNotificationMessage').delay(3000).fadeOut(2000);

}

//CreaTtes a dialog for removing wallposts
$("#removeWallDialog").dialog({
    autoOpen: false
});

//Opens the dialog for writing a new message
function newMessage() {
    
    $('#newMessageDialog').dialog({
        modal: true,
        height: 400,
        width: 600,
        resizable: false,
        draggable: false,
        open: function (type, data) {
            $('#messages-foundUserStatus').attr('class', 'foundUserStatusHidden');
            $(this).parent().appendTo("form");

            $('#MainContent_messagestxtRecipient').val('');
            $('#MainContent_messagestxtMessage').val('');
            $('#MainContent_messagestxtRecipient').focus();
        }
    });
}

//Closes message
function closeNewMessage() {
    $('#newMessageDialog').dialog();
}

//Displays a dialogbox for deleting account
function showDeleteAccountDialog() {
    $("#deleteAccountDialog").dialog({
        modal: true,
        resizable: false,
        draggable: false,
        buttons: {
            'Jag vill avsluta mitt konto': function () {
                location.href = 'Settings.aspx?action=DeleteUser';
            },
            'Nej för f*n! Avbryt!': function () {
                $(this).dialog('close');
            }
        }
    });
}

//Shows the dialog that removes a wallpost
function showRemoveWallDialog(id) {
    $("#removeWallDialog").dialog({
        modal: true,
        resizable: false,
        draggable: false,
        buttons: {
            'Ta bort': function () {
                location.href = '?action=RemoveWallpost&ID=' + id;
            },
            'Avbryt': function () {
                $(this).dialog('close');
            }
        }
    });
}

//Shows the "nördometer", which visually shows the matching between 2 users
function showBar(matchpoint) {
    $("#progressbar").progressbar({
        value: matchpoint
    });
}

//Shows the form that lets the user go premium
function showPurchasePremium() {
    $('#settingsGetPremium').slideDown();
}


function showAddFriendContainer() {
    $('.addFriend').animate({ height: "80px" });
    $('#addFriendContainer').slideDown();
}

//Triggers when a user want to look att the messages that has been sent to/from another user
function showConversation(id) {
    this.location.href = '?action=ViewConversation&user=' + id;
}

//Highlights a user in the message section when clicked
function highlightContact(id) {
    $('div[id^="contact_"]').not('#contact_' + id).attr('class', 'messagesContact');
    $('#contact_' + id).attr('class', 'messagesContactSelected');
}

//Removes an interest from cui context
function removeInterest(id, name) {
    if ($('#MainContent_ddlAvailableInterests option:selected').val() == "Du är intresserad av allt!")
    { $('#MainContent_ddlAvailableInterests option:selected').remove(); }

    $('#MainContent_ddlAvailableInterests').attr("disabled", false);

    $('#interest_' + id).fadeOut(150, function () { $(this).remove() });
    $('#MainContent_ddlAvailableInterests').append(
        $('<option></option>').val(id).html(decodeURIComponent(name))
        );

    $('#hidden_selectedInterests').attr('value', $('#hidden_selectedInterests').val().replace(id + ',', ''));
    $('#addInterestIcon').show();
}

//When a user edits his profile, this method adds the new interest to the profile
function addInterest(nameFromProfile, idFromProfile) {

    var name;
    var id;

    if (nameFromProfile == null && idFromProfile == null) {
        name = $('#MainContent_ddlAvailableInterests option:selected').text();
        id = $('#MainContent_ddlAvailableInterests option:selected').val();
    }
    else {
        name = nameFromProfile;
        id = idFromProfile;
    }

    var newItemNumber = parseInt($('#hidden_selectedInterests').val()) + 1;

    var newItem = "<div id='interest_" + id + "'>" + name +
        "<img src='/images/icons/cross.png' class='interestCrossIcon' id='remove_" + id + "'"
        + " onClick=removeInterest('" + id + "','" + encodeURIComponent(name) + "') />"
        + "<input type='hidden' name='interest" + newItemNumber + "' value='" + id + name + "' /></div>";

    $('#interestsContainer').append(newItem).show();
    $('#interest_' + id).addClass('interestItem');

    $("#MainContent_ddlAvailableInterests option[value='" + id + "']").remove();

    $("#hidden_selectedInterests").val($("#hidden_selectedInterests").val() + id + ",");

    if ($('#MainContent_ddlAvailableInterests option:selected').length == 0) {
        $('#MainContent_ddlAvailableInterests').append(
            $('<option></option>').val('Du är intresserad av allt!').html("Du är intresserad av allt!")
            );
        $('#MainContent_ddlAvailableInterests').attr("disabled", "disabled");
        $('#addInterestIcon').hide();
    }
}

//Displays all interests to chose from in a search
function addSearchInterest(id, name) {

    var newItem = '<div class="searchInterestItem interestItemDeselected" onclick=toggleSelectedInterests(' + id + ')'
        + ' id="interest' + id + '"><input type="hidden" name="' + id + '" id="' + id + '" value="false" />' + name + '</div>';

    $('#interestsContainer').append(newItem);

}

//Displays the interests on the search page depending on if the user has selected them or not
function toggleSelectedInterests(id) {

    $('#interest' + id).toggleClass('interestItemSelected');

    if ($('#interest' + id).hasClass('interestItemSelected')) {
        $('#hiddenSelectedInterests').val($('#hiddenSelectedInterests').val() + id + ',');
    }
    else {
        $('#hiddenSelectedInterests').val($('#hiddenSelectedInterests').val().replace(id + ',', ''));
    }
}

//When a non-premium member tries to get access to premium info, this dialog is displayed
function pleaseUpgrade(message) {

    $('#pleaseUpgrade').html(message);
    $('#pleaseUpgrade').dialog({
        modal: true,
        height: 250,
        width: 350,
        resizable: false,
        draggable: false,
        buttons: {
            'Uppgradera nu!': function () {
                location.href = 'Settings.aspx';
            },

            'Avbryt': function () {
                $(this).dialog("close");
            }
        },
        open: function (type, data) {
            $('#pleaseUpgrade').fadeIn("fast");
        }
    });
    return false;
}

//Click test on premium page
var counter;
var numberOfClicks = 0;
var count = 0;

function btnClick() {
    if (count == 0) {
        timer();
        counter = setInterval(timer, 1000);
    }
    numberOfClicks++;
    console.log(numberOfClicks);
    $('#clicks').text(numberOfClicks);
    return false;
}


function timer() {
    count++;
    if (count == 16) {
        location.href = '?action=gameover&result=' + numberOfClicks;
        return;
    }
    $('#timer').text('Sekunder kvar: ' + (16 - count));
    return false;
}
